<?php
Page::$need_view = false;
ini_set('date.timezone', 'Asia/Shanghai');
error_reporting(0);
file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).':百度回调',FILE_APPEND);
$attach = json_decode($_POST['returnData'], true);
$wid = $attach['wid'];
//支付参数
$payParams = db_query("SELECT * FROM bd_vshop_weixin_pay WHERE wid=?", [$wid])[0];
require_once DOXCX_FRAME_PATH . "/fun/baiduSdk/Autoloader.php";
$rsaPublicKeyStr = $payParams['publicKey'];
//校验签名
$checkSignRes = NuomiRsaSign::checkSignWithRsa($_POST, $rsaPublicKeyStr);
if(!$checkSignRes){
	echo json_encode(array("errno"=>1,"msg"=>"签名错误","data"=>array("isConsumed"=>1)));
	exit();
}
$m = new Model('vshop_order');
$m->find(['wid' => $wid, 'OrderNo' => $_POST['orderId']]);
if ($m->id && $m->PayStatus == 0) {//未支付
        $m->PayStatus = 1;
        $m->tradeNo = $_POST['orderId'];
        $m->pay_time = $_POST['payTime'];
        $item = json_decode($m->items);
        foreach ($item as $_ite) {
          $pro = new Model('vshop_product');
          $pro->field('id,store_nums,sale_nums,rowtemp')->find($_ite->ProductId);
          if ($pro->id) {
            $store_nums = intval($pro->store_nums) - intval($_ite->Count);
            if ($store_nums <= 0) {
              $store_nums = 0;
            }
            $sale_nums = intval($pro->sale_nums) + intval($_ite->Count);//增加销量
            $rowtemp = $this->getRowtemp($_ite->ProductId, $_ite->goods_no, $_ite->Count);//减少属性里面库存
            $pro->update(['id' => $pro->id], ['store_nums' => $store_nums, 'sale_nums' => $sale_nums, 'rowtemp' => $rowtemp]);
          }
        }
        $rs = $m->save();
        // 打印小票
        try{
          print_shop_order($m->id);
        }catch (Exception $e){}
        // 发送短信
        try{
          $cfg=(new Model('vshop_order_task'))->find(['wid'=>$wid]);
          $pub=(new Model('pubs'))->find(['id'=>$wid]);
          if($cfg->id && $cfg->is_sms_notify==1){
            send_sms($pub->uid, $cfg->sms_notify_phone, '【有用户下单啦，快去看看吧】'.'订单号：'.$m->OrderNo.'；订单金额：'.$m->payAmount);
          }
        }catch (Exception $e){}

        if ($rs->id && $rs->sid) {
          //佣金
          $this->getTypes($rs);
        }
		//返回结果
		echo json_encode(array("errno"=>0,"msg"=>"success","data"=>array("isConsumed"=>2)));
   } else {
       //返回结果
		echo json_encode(array("errno"=>1,"msg"=>"订单找不到或已支付","data"=>array("isConsumed"=>1)));
}
	  
  //重置商品属性
   function getRowtemp($id, $goods_no, $Count){
    $arr = [];
    $pro = new Model('vshop_product');
    $pro->field('id,rowtemp')->find($id);
    if ($pro->has_id()) {
      $rowtemp = json_decode($pro->rowtemp);
      $i = 0;
      foreach ($rowtemp as $_v) {
        $arr[$i]['goods_no'] = $_v->goods_no;
        $arr[$i]['spec_array'] = $_v->spec_array;
        if ($_v->store_nums <= 0) {
          $_v->store_nums = 0;
        }
        if ($_v->goods_no == $goods_no) {
          $num = intval($_v->store_nums) - intval($Count);
          if ($num <= 0) {
            $num = 0;
          }
          $arr[$i]['store_nums'] = strval($num);
        } else {
          $arr[$i]['store_nums'] = strval($_v->store_nums);
        }
        $arr[$i]['market_price'] = $_v->market_price;
        $arr[$i]['sell_price'] = $_v->sell_price;
        $arr[$i]['cost_price'] = $_v->cost_price;
        $arr[$i]['weight'] = $_v->weight;
        $i++;
      }
    }
    $arra = json_encode($arr);
    return $arra;
  }
  
  
   //返利佣金
  function getTypes($order){
    $setting = (new Model('vshop_vagent_setting'))->where(['wid' => $order->wid])->find();
    $me = (new Model('vshop_member'))->where(['wxid' => $order->wxid])->find();//下单的用户
    $pm = (new Model('vshop_member'))->where(['id' => $me->pid])->find();//上级用户
    if ($pm->id) {
      //上级返利
      $level1_add = floor($order->payAmount * $setting->level1) / 100;
      $pm->money = $pm->money + $level1_add;
      $pm->unextract_money = $pm->unextract_money + $level1_add;
      $pm->save();
      $blog1 = new Model('vshop_brokerage');
      $blog1->wid = $order->wid;
      $blog1->wxid = $pm->wxid;
      $blog1->orderid = $order->id;
      $blog1->sid = $me->id;
      $blog1->level = 1;
      $blog1->ctime = date('Y-m-d H:i:s');
      $blog1->money = $level1_add;
      $blog1->status = 1;
      $blog1->save();
      $ppm = (new Model('vshop_member'))->where(['id' => $me->pid])->find();//上上级用户
      if ($ppm->id) {
        // 上上级返利
        $level2_add = floor($order->payAmount * $setting->level2) / 100;
        $pm->money = $pm->money + $level2_add;
        $pm->unextract_money = $pm->unextract_money + $level2_add;
        $pm->save();
        $blog2 = new Model('vshop_brokerage');
        $blog2->wid = $order->wid;
        $blog2->wxid = $ppm->wxid;
        $blog2->orderid = $order->id;
        $blog2->sid = $me->id;
        $blog2->level = 2;
        $blog2->ctime = date('Y-m-d H:i:s');
        $blog2->money = $level2_add;
        $blog2->status = 1;
        $blog2->save();
      }
    }
  }